package com.weiya.controller;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.weiya.entity.Role;
import com.weiya.entity.User;
import com.weiya.model.UpdatePasswordVo;
import com.weiya.response.*;
import com.weiya.service.RoleService;
import com.weiya.service.UserService;
import com.weiya.system.shiro.PasswordHelper;
import com.weiya.system.shiro.SystemUserRealm;
import com.weiya.util.UUIDUtil;
import org.apache.shiro.SecurityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.*;

/**
 * <p class="detail">
 * 功能:用户管理
 * </p>
 *
 * @author BaoWeiwei
 * @ClassName User controller.
 * @Version V1.0.
 * @date 2018.07.23 16:55:41
 */
@Controller
@RequestMapping("/user")
public class UserController {

    private static Logger logger = LoggerFactory.getLogger(UserController.class);

    @Autowired
    private UserService userService;
    @Autowired
    private RoleService roleService;
    @Autowired
    private SystemUserRealm userRealm;

    /**
     * <p class="detail">
     * 功能:根据参数查询，初始化用户列表信息
     * </p>
     *
     * @param user   :
     * @param limit  :
     * @param offset :
     * @return page result vo
     * @author BaoWeiwei
     * @date 2018.07.23 16:55:41
     */
    @PostMapping("/list")
    @ResponseBody
    public PageResultVo loadUsers(User user, Integer limit, Integer offset){
        PageHelper.startPage(PageUtil.getPageNo(limit, offset),offset);
        List<User> userList = userService.selectUsers(user);
        PageInfo<User> pages = new PageInfo<>(userList);
        return ResponseUtil.table(userList,pages.getTotal());
    }

    /**
     * <p class="detail">
     * 功能:新增用户
     * </p>
     *
     * @param newUser        :
     * @param confirmPassword :
     * @return response vo
     * @author BaoWeiwei
     * @date 2018.07.23 16:55:41
     */
    @PostMapping("/add")
    @ResponseBody
    public ResponseVo add(User newUser, String confirmPassword){
        String username = newUser.getUsername();
        User user = userService.selectByUsername(username);
        if (null != user) {
            return ResponseUtil.error(ResponseCode.USERNAME_ALREADY_EXIST.getCode(),ResponseCode.USERNAME_ALREADY_EXIST.getMsg());
        }
        String password = newUser.getPassword();
        //判断两次输入密码是否相等
        if (confirmPassword != null && password != null) {
            if (!confirmPassword.equals(password)) {
                return ResponseUtil.error(ResponseCode.PASSWPRD_DIFFERENT.getCode(),ResponseCode.PASSWPRD_DIFFERENT.getMsg());
            }
        }
        newUser.setUserId(UUIDUtil.getUniqueIdByUUId());
        newUser = PasswordHelper.encryptPassword(newUser);
        newUser.setStatus(SystemConst.DATA_VALID);
        Date date = new Date();
        newUser.setCreateTime(date);
        newUser.setUpdateTime(date);
        newUser.setLastLoginTime(date);
        int num = userService.register(newUser);
        if(num > 0){
            return ResponseUtil.success("添加用户成功");
        }else {
            return ResponseUtil.error("添加用户失败");
        }
    }

    /**
     * <p class="detail">
     * 功能:删除用户，状态置为无效
     * </p>
     *
     * @param userId :
     * @return response vo
     * @author BaoWeiwei
     * @date 2018.07.23 17:53:56
     */
    @GetMapping("/delete")
    @ResponseBody
    public ResponseVo delete(String userId) {
        List<String> userIdsList = Arrays.asList(userId);
        int a = userService.updateStatusBatch(userIdsList,SystemConst.DATA_DELETED);
        if (a > 0) {
            return ResponseUtil.success("删除用户成功");
        } else {
            return ResponseUtil.error("删除用户失败");
        }
    }

    /**
     * <p class="detail">
     * 功能:批量删除用户
     * </p>
     *
     * @param userIdStr :
     * @return response vo
     * @author BaoWeiwei
     * @date 2018.07.24 07:46:07
     */
    @GetMapping("/batch/delete")
    @ResponseBody
    public ResponseVo batchDelete(String userIdStr) {
        String[] userIds = userIdStr.split(",");
        List<String> userIdsList = Arrays.asList(userIds);
        int a = userService.updateStatusBatch(userIdsList,SystemConst.DATA_DELETED);
        if (a > 0) {
            return ResponseUtil.success("删除用户成功");
        } else {
            return ResponseUtil.error("删除用户失败");
        }
    }


    /**
     * <p class="detail">
     * 功能:根据用户id加载用户信息
     * </p>
     *
     * @param model  :
     * @param userId :
     * @return string
     * @author BaoWeiwei
     * @date 2018.07.24 10:44:45
     */
    @GetMapping("/edit/{userId}")
    public String detail(Model model, @PathVariable("userId") String userId){
        User user = userService.selectByUserId(userId);
        model.addAttribute("user", user);
        return "user/detail";
    }


    /**
     * <p class="detail">
     * 功能:修改用户信息
     * </p>
     *
     * @param userForm :
     * @return response vo
     * @author BaoWeiwei
     * @date 2018.07.24 10:46:01
     */
    @PostMapping("/edit")
    @ResponseBody
    public ResponseVo editUser(User userForm){
        int a = userService.updateByUserId(userForm);
        if (a > 0) {
            return ResponseUtil.success("修改用户信息成功！");
        } else {
            return ResponseUtil.error("修改用户信息失败");
        }
    }


    /**
     * <p class="detail">
     * 功能:分配角色列表查询
     * </p>
     *
     * @param userId :
     * @return map
     * @author BaoWeiwei
     * @date 2018.07.24 11:32:40
     */
    @PostMapping("/assign/role/list")
    @ResponseBody
    public Map<String,Object> assignRoleList(String userId){
        List<Role> roleList = roleService.selectRoles(new Role());
        Set<String> hasRoles = roleService.findRoleByUserId(userId);
        Map<String, Object> jsonMap = new HashMap<>(2);
        jsonMap.put("rows", roleList);
        jsonMap.put("hasRoles",hasRoles);
        return jsonMap;
    }

    /**
     * <p class="detail">
     * 功能:分配用户角色
     * </p>
     *
     * @param userId    :
     * @param roleIdStr :
     * @return response vo
     * @author BaoWeiwei
     * @date 2018.07.24 11:50:53
     */
    @PostMapping("/assign/role")
    @ResponseBody
    public ResponseVo assignRole(String userId, String roleIdStr){
        String[] roleIds = roleIdStr.split(",");
        List<String> roleIdsList = Arrays.asList(roleIds);
        ResponseVo responseVo = userService.addAssignRole(userId,roleIdsList);
        List<String> userIds = new ArrayList<>();
        userIds.add(userId);
        userRealm.clearAuthorizationByUserId(userIds);
        return responseVo;
    }


    /**
     * <p class="detail">
     * 功能:修改密码功能
     * </p>
     *
     * @param updatePasswordVo :
     * @return response vo
     * @author BaoWeiwei
     * @date 2018.07.25 13:49:23
     */
    @RequestMapping(value = "/password/change",method = RequestMethod.POST)
    @ResponseBody
    public ResponseVo changePassword(UpdatePasswordVo updatePasswordVo) {
        if(!updatePasswordVo.getNewPassword().equals(updatePasswordVo.getConfirmNewPassword())){
            return ResponseUtil.error("两次密码输入不一致");
        }
        User loginUser = userService.selectByUserId(((User) SecurityUtils.getSubject().getPrincipal()).getUserId());
        User newUser = new User();
        BeanUtils.copyProperties(loginUser,newUser);
        String sysOldPassword = loginUser.getPassword();
        newUser.setPassword(updatePasswordVo.getOldPassword());
        String entryOldPassword = PasswordHelper.getPassword(newUser);
        if(sysOldPassword.equals(entryOldPassword)){
            newUser.setPassword(updatePasswordVo.getNewPassword());
            newUser = PasswordHelper.encryptPassword(newUser);
            int result = userService.updateUserByPrimaryKey(newUser);
            if(result < 1){
                return ResponseUtil.error("修改密码失败，请重试！");
            }
            //*清除登录缓存*//
            List<String> userIds = new ArrayList<>();
            userIds.add(loginUser.getUserId());
            userRealm.clearCachedAuthenticationInfo(userIds);
        }else{
            return ResponseUtil.error("您输入的旧密码有误！");
        }
        return ResponseUtil.success("修改密码成功！");
    }
}
